package com.GithubMeizhis;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.GithubMeizhis.adapter.MeizhiListAdapter;
import com.GithubMeizhis.base.SwipeRefreshBaseActivity;
import com.GithubMeizhis.entity.Gank;
import com.GithubMeizhis.entity.Meizhi;
import com.GithubMeizhis.entity.MeizhiData;
import com.GithubMeizhis.entity.休息视频Data;
import com.GithubMeizhis.util.AXLog;
import com.GithubMeizhis.util.Dates;
import com.GithubMeizhis.util.Once;
import com.GithubMeizhis.util.Toasts;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

import static com.GithubMeizhis.GankActivityMy.EXTRA_GANK_DATE;
import static com.GithubMeizhis.GankActivityMy.EXTRA_IMG_DATE;


public class MainActivity extends SwipeRefreshBaseActivity {
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    private CoordinatorLayout coor;
    private RecyclerView recycle;
    private int mLastVideoIndex = 0;
    private CompositeSubscription mCompositeSubscription;
    private Context context;
    private List<Meizhi> mMeizhiList = new ArrayList<>();
    MeizhiListAdapter mMeizhiListAdapter;
    static Activity activity;

    final static Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
            .serializeNulls()
            .create();
    private boolean mIsFirstTimeTouchBottom = true;
    private int mPage = 1;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setSupportActionBar(toolbar);
        context = this;
//        setContentView(R.layout.activity_main);
        AXLog.e("wzytest", "oncreate :" + Thread.currentThread().getName());

        setUpRecycleView();

        //asYrx();
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        new Handler().postDelayed(() -> setRefresh(true), 358);
        AXLog.e("wzytest", "onPostCreate :" + Thread.currentThread().getName());
        loadData(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        AXLog.e("wzytest", "onResume :" + Thread.currentThread().getName());
    }

    @Override
    protected void onStart() {
        super.onStart();
        AXLog.e("wzytest", "onStart :" + Thread.currentThread().getName());
    }

    private void startGankActivity(String url , Meizhi meizhi,Date publishedAt) {
        AXLog.e("wzytest","run in startGankActivity");
        Intent intent = new Intent(this, GankActivityMy.class);
        intent.putExtra(EXTRA_GANK_DATE, publishedAt);
        intent.putExtra(EXTRA_IMG_DATE, meizhi.url);
        startActivity(intent);
    }

    private void startPicActivity(String url , Meizhi meizhi) {
        AXLog.e("wzytest","run in startPicActivity");
        Intent intent = new Intent(this, PicActivity.class);
        intent.putExtra(PicActivity.EXTRA_IMAGE_URL, url);
        intent.putExtra(PicActivity.EXTRA_IMAGE_TITLE, meizhi.desc);
        startActivity(intent);
    }

    private void setUpRecycleView() {
        final StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2,
                StaggeredGridLayoutManager.VERTICAL);

        recycle = (RecyclerView) findViewById(R.id.list);
        recycle.setLayoutManager(layoutManager);
        mMeizhiListAdapter = new MeizhiListAdapter(context, mMeizhiList);
        mMeizhiListAdapter.setOnItemclickListner(
                new MeizhiViewHolderOnclick() {
                    @Override
                    public void onMeiZhiclik(View view,String url, Meizhi meizhi) {
                        if(view.getId()==R.id.tv_meizhi_item)
                            startGankActivity(url,meizhi,meizhi.publishedAt);
                        if(view.getId()==R.id.iv_meizhi_item)
                            startPicActivity(url,meizhi);
                    }
                }
        );
        recycle.setAdapter(mMeizhiListAdapter);

//        new Once(this).show("tip_guide_6", () -> {
            Snackbar.make(recycle, getString(R.string.tip_guide), Snackbar.LENGTH_INDEFINITE)
                    .setAction(R.string.i_know, v -> {
                    })
                    .show();
//        });

        recycle.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                boolean isBottom =
                        layoutManager.findLastCompletelyVisibleItemPositions(new int[2])[1] >=
                                mMeizhiListAdapter.getItemCount() - 6;
                int[] ints = layoutManager.findLastCompletelyVisibleItemPositions(new int[2]);
//                AXLog.e("wzytest", ints[0] + ":" + ints[1] + ":" + mMeizhiListAdapter.getItemCount());
//
//                AXLog.e("wzytest", mSwipeRefreshLayout.isRefreshing() + "：" + isBottom + "：" + mIsFirstTimeTouchBottom);
                if (!mSwipeRefreshLayout.isRefreshing() && isBottom) {

                    if (!mIsFirstTimeTouchBottom) {
                        mSwipeRefreshLayout.setRefreshing(true);
                        mPage += 1;
                        loadData(false);
                    } else {
                        mIsFirstTimeTouchBottom = false;
                    }
                }
            }
        });

    }



    @Override
    public void requestDataRefresh() {
        super.requestDataRefresh();
        AXLog.e("wzytest", "run in requestDataRefresh");
//        mPage = 1;
        loadData(true);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }

    public void loadData(boolean clean) {
        AXLog.e("wzytest", "loaddata........");
        mLastVideoIndex = 0;
        Subscription sub = Observable
                .zip(MyMeizhiFactory.getsGankIOSingleton().getMeizhiData(mPage),
                        MyMeizhiFactory.getsGankIOSingleton().get休息视频Data(mPage),
                        this::createMeizhiDataWith休息视频Desc
                )
//                .map(new Func1<MeizhiData, List<Meizhi>>() {
//
//                    @Override
//                    public List<Meizhi> call(MeizhiData meizhiData) {
//                        return null;
//                    }
//                })
                .map(m -> m.results)
                .flatMap(
                        new Func1<List<Meizhi>, Observable<Meizhi>>() {
                            @Override
                            public Observable<Meizhi> call(List<Meizhi> meizhis) {
                                return Observable.from(meizhis);
                            }
                        }).toSortedList(
                        (meizhi, meizhi2) -> {
                            return meizhi.publishedAt.compareTo(meizhi2.createdAt);
                        })
//                    .flatMap(new Func1<List<Meizhi>, Observable<Meizhi>>() {
//                        @Override
//                        public Observable<Meizhi> call(List<Meizhi> meizhis) {
//                            return Observable.from(meizhis);
//                        }
//                    })
                .doOnNext(meizhis -> saveMeizhi())
                .finallyDo(() -> setRefresh(false))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
//            .observeOn(Schedulers.io())
                .subscribe(meizhis -> {
                            if (clean) {
                                mMeizhiList.clear();
                            }
                            AXLog.e("wzytest", "获取到妹纸一条信息：" + meizhis);
                            mMeizhiList.addAll(meizhis);
//                            for (int i = 0; i < meizhis.size(); i++) {
//                                AXLog.e("wzytest", "获取到信息" + i + ":" + meizhis.get(i));
//                            }
                            mMeizhiListAdapter.notifyDataSetChanged();
                        }, throwable -> loadErr(throwable)
                );
        addSubscription(sub);
    }

    private void loadErr(Throwable throwable) {
        AXLog.e("wzytest", "rxjava 获取结果失败");
        throwable.printStackTrace();
//        Snackbar.make(mRecyclerView, R.string.snap_load_fail, Snackbar.LENGTH_LONG)
//                .setAction(R.string.retry, v -> {
//                    requestDataRefresh();
//                })
//                .show();
    }

    private void saveMeizhi() {
        AXLog.e("wzytest", "run in saveMeizhi:" + Thread.currentThread().getName());
    }

    private MeizhiData createMeizhiDataWith休息视频Desc(MeizhiData data, 休息视频Data love) {
        for (Meizhi meizhi : data.results) {
            meizhi.desc = meizhi.desc + " " +
                    getFirstVideoDesc(meizhi.publishedAt, love.results);
        }
        return data;
    }

    private String getFirstVideoDesc(Date publishedAt, List<Gank> results) {
        String videoDesc = "";
        for (int i = mLastVideoIndex; i < results.size(); i++) {
            Gank video = results.get(i);
            if (video.publishedAt == null) video.publishedAt = video.createdAt;
            if (Dates.isTheSameDay(publishedAt, video.publishedAt)) {
                videoDesc = video.desc;
                mLastVideoIndex = i;
                break;
            }
        }
        return videoDesc;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        AXLog.e("wzytest","创建菜单项目");
        getMenuInflater().inflate(R.menu.menu_about, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        switch (id) {
            case R.id.login:
                loginGitHub();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    protected void loginGitHub() {
        new Once(this).show(R.string.action_github_login, () -> {
            Toasts.showLongX2(getString(R.string.tip_login_github));
        });
        String url = getString(R.string.url_login_github);
        Intent intent = WebActivity.newIntent(this, url,
                getString(R.string.action_github_login));
        startActivity(intent);
    }

//
//    @Override public void onToolbarClick() {recycle.smoothScrollToPosition(0);}
}
